/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.context.ActionContextHolder;
import com.lmx.persistence.service.AccountService;
import com.lmx.repoDomain.tmodel.RechargeRecord;
import com.lmx.repoDomain.tmodel.TradeAccount;

import javax.annotation.PostConstruct;

@JsonApiResourceRepository(RechargeRecord.class)
@Component
public class RechargeRecordRepository extends BaseRepository<RechargeRecord> {

	@Autowired
	protected AccountService accountService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(RechargeRecord.class);
	}

	@Override
	@JsonApiSave
	public RechargeRecord save(RechargeRecord record) {
		if (record.getId() == null) {
			dslJpaService.create(record);
		} else {
			if (record.getDelStatus() == 1) {
				dslJpaService.update(record);
				return record;
			} else {
				RechargeRecord oldRecord = accountService.getRechargeRecordById(record.getId());
				// 审核通过
				if (oldRecord.getRechargeStatus() != null && record.getRechargeStatus() != null
						&& "rechargeStatus1".equals(oldRecord.getRechargeStatus().getTypecode())
						&& "rechargeStatus2".equals(record.getRechargeStatus().getTypecode())) {
					// 客户账户
					TradeAccount customerAccount = record.getRechargeAccount();
					// 所属机构账户
					TradeAccount orgAccount = accountService
							.getTradeAccountByOrg(ActionContextHolder.getContext().getUser().getOrg().getId());
					if (customerAccount != null && orgAccount != null) {
						// 修改账户余额并生成交易记录
						record = accountService.updateRechargeRecord(record, customerAccount, orgAccount);
						return record;
					} else {
						record.setErrcode(0);// 失败
						return record;
					}
				}
				dslJpaService.update(record);
			}

		}
		return record;

	}
}
